package com.algorithm;

/**
 * @author Jack
 * @description: 给定一个已按照 非递减顺序排列  的整数数组 numbers ，请你从数组中找出两个数满足相加之和等于目标数 target 。
 * @date 2021/8/31 13:55
 */
public class DoublePointer {

    /**
     * 方法一
     *
     * @param numbers
     * @param target
     * @return:
     * @author: jack
     * @date 2021/8/31 13:56
     */
    public int[] twoSum1(int[] numbers, int target) {
        int left = 0, right = numbers.length - 1;

        while (left < right) {
            int sum = numbers[left] + numbers[right];
            if (sum == target) {
                return new int[]{left + 1, right + 1};
            }
            if (sum > target) {
                right--;
            } else {
                left++;
            }
        }
        return new int[]{-1, -1};
    }

    /**
     * 方法二
     * 使用二分法
     *
     * @param numbers
     * @param target
     * @return:
     * @author: jack
     * @date 2021/8/31 14:51
     */
    public int[] twoSum2(int[] numbers, int target) {
        for (int i = 0; i < numbers.length; i++) {
            int left = i, right = numbers.length - 1;
            while (left <= right) {
                int mid = (right - left) / 2 + left;
                if (numbers[mid] == target - numbers[i]) {
                    return new int[]{i + 1, mid + 1};
                }
                if (target - numbers[left] > numbers[mid]) {
                    left = mid + 1;
                } else {
                    right = mid - 1;
                }
            }
        }
        return new int[]{-1, -1};
    }


    public static void main(String[] args) throws Exception {
        int[] numbers = {2, 3, 4, 4, 4, 5, 7, 12};
        int target = 6;

        //int[] nums = DoublePointer.class.newInstance().twoSum1(numbers, target);
        int[] nums = DoublePointer.class.newInstance().twoSum2(numbers, target);
        for (int i : nums) {
            System.out.println(i);
        }

        int i=3;
        int b=i++;
        int c=++i;

        System.out.println(b);
        System.out.println(c);
    }
}
